<template>
  <Container class="single-sale">
    <div slot="header" class="container-header title title-center">选择赠品</div>
    <div class="bg-light mt">
      <div class="container-header">
        <SearchSale @onSearchData="onSearchData" />
      </div>
      <Tabs v-model="ChoiceGifts">
        <Button v-if="hasGift2" slot="extra" class="item" type="primary" @click="onJoinAdd(1)">一阶赠品</Button>
        <Button v-if="hasGift2" slot="extra" class="item" type="primary" @click="onJoinAdd(2)">二阶赠品</Button>
        <Button v-if="hasGift3" slot="extra" class="item" type="primary" @click="onJoinAdd(3)">三阶赠品</Button>
        <Button
          v-if="hasPatchAdd && ChoiceGifts == 'ChoiceGifts1'"
          slot="extra"
          class="item"
          type="primary"
          icon="md-add"
          @click="onJoinAdd(1)"
        >批量加入</Button>
        <Button
          v-if="ChoiceGifts !== 'ChoiceGifts1'"
          slot="extra"
          class="item"
          type="primary"
          icon="md-add"
          @click="onJoinDelete"
        >批量删除</Button>
        <TabPane label="选择赠品" name="ChoiceGifts1">
          <choicePrevent ref="choicePrevent" />
        </TabPane>
        <TabPane v-if="hasGift1" :label="label1" name="ChoiceGifts2">
          <present ref="prevent" />
        </TabPane>
        <TabPane v-if="hasGift2" :label="label2" name="ChoiceGifts3">
          <present1 ref="prevent1" />
        </TabPane>
        <TabPane v-if="hasGift3" :label="label3" name="ChoiceGifts4">
          <present2 ref="prevent2" />
        </TabPane>
      </Tabs>
    </div>
    <div slot="footer" class="container-footer bg-white">
      <Button size="large" @click="jumpPrevPage">返回</Button>
      <Button type="primary" size="large" class="ml" :loading="loading" @click="onJoinPrevent">保存</Button>
    </div>
  </Container>
</template>
<script>
import choicePrevent from './list/ChoicePrevent.vue'
import present from './list/present.vue'
import present1 from './list/present1.vue'
import present2 from './list/present2.vue'
import SearchSale from '@/views/sales/common/SearchSale'
import { formatDate, getGift } from './list/FullGiftListMethods'
import { getPuduct } from '@/views/sales/common/TableSaleMethods'
export default {
  components: {
    choicePrevent,
    present,
    present1,
    present2,
    SearchSale
  },
  props: {
    form: {
      type: Object
    }
  },
  data () {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      tab: 'tab1',
      loading: false,
      ChoiceGifts: 'ChoiceGifts1',
      rule: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
        sku: [{ required: true, message: '请输入SKU编码', trigger: 'blur' }]
      },
      setForm: {
        type: '1',
        discountNum: 5,
        subNum: 0,
        saleNum: 0
      },
      label1: (h) => {
        return h('div', [
          h('span', this.ChoiceGifts2),
          h('Badge', {
            props: {
              count: this.ChoiceGifts2 ? this.gift1Num : ''
            }
          })
        ])
      },
      label2: (h) => {
        return h('div', [
          h('span', this.ChoiceGifts3),
          h('Badge', {
            props: {
              count: this.ChoiceGifts3 ? this.gift2Num : ''
            }
          })
        ])
      },
      label3: (h) => {
        return h('div', [
          h('span', this.ChoiceGifts4),
          h('Badge', {
            props: {
              count: this.ChoiceGifts4 ? this.gift3Num : 0
            }
          })
        ])
      }
    }
  },
  computed: {
    hasPatchAdd () {
      return this.$store.getters.hasPatchAdd
    },
    gift1Num () {
      return this.$store.getters.getFullGiftSaleGift1Num || 0
    },
    gift2Num () {
      return this.$store.getters.getFullGiftSaleGift2Num || 0
    },
    gift3Num () {
      return this.$store.getters.getFullGiftSaleGift3Num || 0
    },
    hasGift1 () {
      return this.$store.getters.hasGift1
    },
    hasGift2 () {
      return this.$store.getters.hasGift2
    },
    hasGift3 () {
      return this.$store.getters.hasGift3
    },
    timeList () {
      return [
        {
          startDatetime: formatDate(
            this.$store.state.fullGiftSale.form.date[0],
            true
          ),
          endDatetime: formatDate(
            this.$store.state.fullGiftSale.form.date[1],
            true
          )
        }
      ]
    },
    fullGiftRuleList () {
      if (this.$store.state.fullGiftSale.form.term == '2') {
        let newArray = []
        this.$store.state.fullGiftSale.form.discount1.map(function (item, index, array) {
          newArray.push({ m: item.value, isParcel: item.isParcel })
        })
        this.$store.state.fullGiftSale.form.discount2.map(function (item, index, array) {
          newArray[index]['n'] = item.value
        })
        return newArray
      } else {
        let newArray = []
        this.$store.state.fullGiftSale.form.discountGift.map(function (item, index, array) {
          newArray.push({ m: item.value, n: 0, isParcel: item.isParcel })
        })
        return newArray
      }
    },
    fullGiftTypeEnum () {
      if (this.$store.state.fullGiftSale.form.term == '1') {
        return 'FULL_GIFT'
      } else {
        return 'ADD_PRICE'
      }
    },
    promotionMemberScope () {
      return this.$store.state.fullGiftSale.form.grade
    },
    productSkuList () {
      return getPuduct(this.$store.state.fullGiftSale.GetsaleData, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'parentcode', 'code']
      })
    },
    giftSkuList () {
      let param1 = getGift(this.$store.state.fullGiftSale.GetgiftData1, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'quantity', 'returnPrice', 'parentcode', 'code', 1]
      })
      let param2 = getGift(this.$store.state.fullGiftSale.GetgiftData2, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'quantity', 'returnPrice', 'parentcode', 'code', 2]
      })
      let param3 = getGift(this.$store.state.fullGiftSale.GetgiftData3, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'quantity', 'returnPrice', 'parentcode', 'code', 3]
      })
      return [...param1, ...param2, ...param3]
    },
    ChoiceGifts2 () {
      return this.$store.getters.ChoiceGifts2
    },
    ChoiceGifts3 () {
      return this.$store.getters.ChoiceGifts3 || ''
    },
    ChoiceGifts4 () {
      return this.$store.getters.ChoiceGifts4 || ''
    }
  },
  mounted () {
    if (this.id && ((this.hasGift1 && !this.$store.state.fullGiftSale.GetgiftData1.length) || (this.hasGift2 && !this.$store.state.fullGiftSale.GetgiftData2.length) || (this.hasGift2 && !this.$store.state.fullGiftSale.GetgiftData3.length))) this.getData()
  },
  methods: {
    setData (data, type) {
      return (data[type] || []).map(item => {
        return {
          id: item.item[0].productId,
          checked: false,
          buttonChecked: false,
          showChildren: false,
          sale: '',
          limitQuantity: '',
          code: item.productSn,
          salePrice: '',
          reduce: '',
          stock: '',
          isShelf: item.isShelf,
          discount: '',
          title: item.title,
          quantity: item.quantity,
          returnPrice: '',
          productSkuList: item.item.map(todo => {
            return {
              id: todo.skuId,
              productId: todo.productId,
              productSn: todo.productSn,
              parentcode: item.productSn,
              checked: false,
              buttonChecked: false,
              showChildren: false,
              limitQuantity: '',
              code: todo.skuSn,
              salePrice: todo.productSkuInfo.salePrice,
              reduce: '',
              sale: todo.promotionPrice,
              isShelf: todo.isShelf,
              discount: '',
              title: '',
              stock: todo.productSkuInfo.stock,
              returnPrice: todo.returnPrice,
              quantity: item.quantity
            }
          })
        }
      })
    },
    getData () {
      let that = this
      this.$ajaxGet(`/activity/activity_gift_sku_list/${this.id}`).then(data => {
        let indexs = that.getStep(data)
        if (indexs[0]) that.$store.state.fullGiftSale['GetgiftData' + indexs[0]] = that.setData(data, 0)
        if (indexs[1]) that.$store.state.fullGiftSale['GetgiftData' + indexs[1]] = that.setData(data, 1)
        if (indexs[2]) that.$store.state.fullGiftSale['GetgiftData' + indexs[2]] = that.setData(data, 2)
        that.onSearchData()
      })
    },
    getStep (data) {
      let newArray = []
      if (data[0] && data[0].length) newArray[0] = data[0][0].groups
      if (data[1] && data[1].length) newArray[1] = data[1][0].groups
      if (data[2] && data[2].length) newArray[2] = data[2][0].groups
      return newArray
    },
    jumpPrevPage () {
      this.$router.back()
    },
    onSearchData (param) {
      this.$refs.choicePrevent.getProductData(param)
    },
    onJoinAdd (type) {
      this.$refs.choicePrevent.getSaleData(type)
    },
    onJoinDelete (type) {
      // 商品删除一阶赠品
      if (this.ChoiceGifts == 'ChoiceGifts2') {
        this.$refs.prevent.deleteSaleData('ChoiceGifts2')
        // 商品删除二阶赠品
      } else if (this.ChoiceGifts == 'ChoiceGifts3') {
        this.$refs.prevent.deleteSaleData('ChoiceGifts3')
        // 商品删除三阶赠品
      } else if (this.ChoiceGifts == 'ChoiceGifts4') {
        this.$refs.prevent.deleteSaleData('ChoiceGifts4')
      }
    },
    onJoinPrevent () {
      let self = this
      if (this.fullGiftRuleList.length == 1) {
        if (!this.$store.state.fullGiftSale.GetgiftData1.length) {
          self.$Message.error('请选择一阶赠品')
          return false
        }
      } else if (this.fullGiftRuleList.length == 2) {
        if (!this.$store.state.fullGiftSale.GetgiftData1.length) {
          self.$Message.error('请选择一阶赠品')
          return false
        }
        if (!this.$store.state.fullGiftSale.GetgiftData2.length) {
          self.$Message.error('请选择二阶赠品')
          return false
        }
      } else if (this.fullGiftRuleList.length == 3) {
        if (!this.$store.state.fullGiftSale.GetgiftData1.length) {
          self.$Message.error('请选择一阶赠品')
          return false
        }
        if (!this.$store.state.fullGiftSale.GetgiftData2.length) {
          self.$Message.error('请选择二阶赠品')
          return false
        }
        if (!this.$store.state.fullGiftSale.GetgiftData3.length) {
          self.$Message.error('请选择三阶赠品')
          return false
        }
      }
      self.loading = true
      let url = '/activity/full_gift/save'
      let param = {
        activityFullGiftDTO: {
          giftProductSkuList: this.giftSkuList,
          fullGiftRuleList: this.fullGiftRuleList,
          fullGiftTypeEnum: this.fullGiftTypeEnum
        },
        activityInfoDTO: {
          activityName: this.$store.state.fullGiftSale.form.name, //活动名称
          activityDescription: this.$store.state.fullGiftSale.form.remarks, //活动备注
          productSkuList: this.productSkuList,
          storeTypeEnumList: this.promotionMemberScope,
          startDate: this.timeList[0].startDatetime,
          endDate: this.timeList[0].endDatetime,
          joinTypeEnum: 'PART',
          shelfStatusEnum: 'ON'
        }
      }
      if (this.id && this.type) {
        url = '/activity/full_gift/edit'
        param.activityFullGiftDTO.activityId = this.id
      }
      this.$jsonPost(url, param).then(data => {
        self.$Message.success((this.id && this.type) ? '编辑活动成功' : '新增活动成功')
        self.$store.commit('setFullGiftSaleEmpty')
        self.loading = false
        self.$router.push({ name: 'sales/list' })
      }).catch(data => {
        self.loading = false
      })
    }
  }
}
</script>
